package com.dsl.dslsuzhou.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 元数据查询服务
 * 提供维度表信息查询功能，支持动态构造DSL查询参数
 */
@Service
public class MetadataService {

    @Autowired
    private JdbcTemplate jdbcTemplate;

    /**
     * 查询所有子系统信息
     */
    public Map<String, Object> getAllSubsystems() {
        String sql = "SELECT subsystem_id, subsystem_name, subsystem_type, parent_id FROM dim_subsystem ORDER BY subsystem_id";
        
        List<Map<String, Object>> subsystems = jdbcTemplate.queryForList(sql);
        
        Map<String, Object> result = new HashMap<>();
        result.put("code", 200);
        result.put("message", "success");
        result.put("data", subsystems);
        return result;
    }

    /**
     * 按类型分组查询子系统
     */
    public Map<String, Object> getSubsystemsByType() {
        String sql = "SELECT subsystem_id, subsystem_name, subsystem_type FROM dim_subsystem ORDER BY subsystem_type, subsystem_id";
        
        List<Map<String, Object>> subsystems = jdbcTemplate.queryForList(sql);
        
        // 按类型分组
        Map<String, List<Map<String, Object>>> groupedByType = subsystems.stream()
            .collect(Collectors.groupingBy(s -> (String) s.get("subsystem_type")));
        
        Map<String, Object> result = new HashMap<>();
        result.put("code", 200);
        result.put("message", "success");
        result.put("data", groupedByType);
        return result;
    }

    /**
     * 查询特定类型的子系统ID列表
     */
    public Map<String, Object> getSubsystemIdsByType(String type) {
        String sql = "SELECT subsystem_id, subsystem_name FROM dim_subsystem WHERE subsystem_type = ? ORDER BY subsystem_id";
        List<Map<String, Object>> subsystems = jdbcTemplate.queryForList(sql, type);
        List<Long> ids = subsystems.stream()
            .map(s -> ((Number) s.get("subsystem_id")).longValue())
            .collect(Collectors.toList());
        
        Map<String, Object> data = new HashMap<>();
        data.put("type", type);
        data.put("subsystem_ids", ids);
        data.put("subsystems", subsystems);
        data.put("count", ids.size());
        
        Map<String, Object> result = new HashMap<>();
        result.put("code", 200);
        result.put("message", "success");
        result.put("data", data);
        return result;
    }
}
